package com.example.handler.excelhander;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

public class MergeStrategy extends AbstractMergeStrategy {

    private int idx1;
    private int idx2;
    public MergeStrategy(int idx1, int idx2) {
        this.idx1 = idx1;
        this.idx2 = idx2;
    }
    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, int relativeRowIndex) {
        int rowIndex = cell.getRowIndex();
        int columnIndex = cell.getColumnIndex();
        if (rowIndex==0 && columnIndex%2==1 && columnIndex>=1 && columnIndex<=3){
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowIndex,
                    rowIndex, columnIndex, columnIndex+1);
            sheet.addMergedRegion(cellRangeAddress);
        }

        if (rowIndex>idx1+1 && rowIndex<=(idx1+idx2+2) && columnIndex%2==0){
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowIndex,
                    rowIndex, columnIndex, columnIndex+1);
            sheet.addMergedRegion(cellRangeAddress);
        }

        if (rowIndex>(idx1+idx2+2) && columnIndex%6==0){
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowIndex,
                    rowIndex, columnIndex, columnIndex+5);
            sheet.addMergedRegion(cellRangeAddress);
        }

        if (rowIndex>(idx1+idx2+3)){
            //建表语句设置行高
            CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.LEFT);
            cellStyle.setVerticalAlignment(VerticalAlignment.TOP);
            cellStyle.setWrapText(Boolean.TRUE);
            cell.setCellStyle(cellStyle);
//            cell.getRow().setHeight((short) 5100);
        }

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, int relativeRowIndex, boolean isHead) {
        merge(writeSheetHolder.getSheet(), cell, head, relativeRowIndex);
    }
}
